package com.manlost.biz.common.ibatis;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.support.DaoSupport;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.manlost.biz.common.query.PageQuery;

@SuppressWarnings("rawtypes")
public class BaseSqlMapClientDaoSupport extends DaoSupport {

    private ManlostSqlMapClientTemplate sqlMapClientTemplate = null;

    private boolean                     externalTemplate     = false;

    public BaseSqlMapClientDaoSupport() {
        sqlMapClientTemplate = new ManlostSqlMapClientTemplate();
    }

    public final void setDataSource(DataSource dataSource) {
        this.sqlMapClientTemplate.setDataSource(dataSource);
    }

    public final DataSource getDataSource() {
        return (this.sqlMapClientTemplate != null ? this.sqlMapClientTemplate.getDataSource() : null);
    }

    @Autowired
    public final void setSqlMapClient(SqlMapClient sqlMapClient) {
        this.sqlMapClientTemplate.setSqlMapClient(sqlMapClient);
    }

    public final SqlMapClient getSqlMapClient() {
        return this.sqlMapClientTemplate.getSqlMapClient();
    }

    public final void setSqlMapClientTemplate(ManlostSqlMapClientTemplate sqlMapClientTemplate) {
        if (sqlMapClientTemplate == null) {
            throw new IllegalArgumentException("Cannot set sqlMapClientTemplate to null");
        }
        this.sqlMapClientTemplate = sqlMapClientTemplate;
        this.externalTemplate = true;
    }

    public final ManlostSqlMapClientTemplate getSqlMapClientTemplate() {
        return sqlMapClientTemplate;
    }

    protected final void checkDaoConfig() {
        if (!this.externalTemplate) {
            this.sqlMapClientTemplate.afterPropertiesSet();
        }
    }

    public PageQueryList queryForPagination(String countStatementName, String queryStatementName, PageQuery query) {
        return this.getSqlMapClientTemplate().queryForPage(countStatementName, queryStatementName, query);
    }

}
